<template>
  <div class="pages stockstagestock" id="app">
    <div class="pageLevel">
      <!-- 操作框 -->
      <div class="operationBox tableSearch" style="margin-left:30px">
        <el-button type="primary" size="mini" :disabled="entered" @click="save()">保存</el-button>
        <el-button type="primary" size="mini" :disabled="entered" @click="addShop()">添加商品</el-button>
        <el-button type="primary" size="mini" v-if='setRole("零期初库存")' :disabled="entered" @click="save('none')">零库存期初</el-button>
        <a href="javascript:;" class="file">
          批量导入
          <input ref="uploading" :disabled="entered" @change="uploading($event)" type="file">
        </a>
        <el-button type="primary" :disabled="entered" size="mini" style="position:relative" @click='download'>
          <!-- <a style="position: absolute;width: 100%;height: 100%;top: 0px;left: 0px;opacity:0" @click=""></a> -->
          下载模板</el-button>
      </div>
      <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
        <el-row>
          <el-col :span="9">
            <el-form-item label="录入仓库：" prop="warehouse">
              <el-select size="small" style="width:200px" v-model="formdata.warehouse" @change="getwarehouseName" placeholder="请先选择录入仓库">
                <el-option v-for="item in options" :key="item.index" :label="item.name" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 表格 -->
      <div class="tableMain">
        <el-table :data="tableData" stripe @selection-change="changeFun_good" style="width: 100%">
          <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="goodsBatchNumber" label="商品批次" align="center" width="150">
            <template slot-scope="scope">
              <span v-if="scope.row.isBatch=='0'">{{"---"}}</span>
              <!-- v-else="startCounting==true" -->
              <!-- <sd-input v-else :val.sync='scope.row.goodsBatchNumber' ></sd-input> -->
              <!-- <input v-else class="commonInput" v-model="scope.row.goodsBatchNumber" size="mini" type="text" value="1" min="1" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^0-9]/g,'')}else if(this.value){this.value=parseInt(this.value.replace(/\D/g,''))}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}"> -->
              <input v-else class="commonInput" v-model="scope.row.goodsBatchNumber" size="mini" type="text" style="width:100px" value="1" min="1" maxlength="16" oninput="value=value.replace(/[\W]/g,'')" onafterpaste="value=value.replace(/[\W]/g,'')">

            </template>
          </el-table-column>
           <!-- 集团订单新加功能5/31 -->
          <el-table-column prop="dateInProduced" label="生产日期" align="center" width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.isBatch=='0'">{{"---"}}</span>
              <el-date-picker size="small" v-else v-model="scope.row.dateInProduced" :picker-options="pickerOptions1" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date"></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品" align="center"></el-table-column>
          <el-table-column prop="primaryClassify" label="商品分类" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.primaryClassify}}</span>
              <!-- <span v-if="scope.row.secondaryName !=''">{{scope.row.secondaryName}}</span>
              <span v-if="scope.row.secondaryName !=''">{{scope.row.threeName}}</span> -->
            </template>
          </el-table-column>
          <el-table-column prop="parameter" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in  scope.row.parameter" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null">{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="" label="仓库" align="center">
            <template slot-scope="">
              <div>{{warehouseName}}</div>
            </template>
          </el-table-column>
          <el-table-column prop="goodsNum" label="期初库存数量" align="center" width="150">
            <template slot-scope="scope">
              <input v-if="startCounting==true" class="commonInput" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="1" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else if(value){this.value=parseInt(this.value.replace(/\D/g,''))}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
              <span v-else>{{scope.row.goodsNum}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="goodsPrice" label="单价" align="center">
            <template slot-scope="scope">
              <sd-input :val.sync='scope.row.goodsPrice' v-if="startCounting==true"></sd-input>
              <span v-else>{{scope.row.goodsPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column label="金额" align="center">
            <template slot-scope="scope">
              <span>{{(Number(scope.row.goodsPrice)*Number(scope.row.goodsNum)).toFixed(2)}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button type="text" v-if="scope.row.name" @click="handleDelete(scope.$index)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="th-right">
        <el-form :model="formdata" :rules="rules" label-width="120px" size="mini">
          <el-row>
            <el-col :span="12">
              <el-form-item label="操作员：">
                <el-input v-model="formdata.creater" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 物料清单弹出框 -->
      <el-dialog title="选择商品" class="addshopname" :visible.sync="dialogTableVisible_good" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
        <i class="el-icon-close icon" @click="dialogTableVisible_good=false"></i>
        <i class="el-icon-close icon" @click="dialogTableVisible_good=false"></i>
        <!-- <add-material :dataList='materielList' :deleteList='tableData' @ww='listenKeyword' @chooseDone='listenChooseDone' @close='dialogTableVisible_good=false'></add-material> -->

        <div class="operationBox tableSearch">
          <el-button size="mini" type="primary" @click="save_good">选择</el-button>
          <el-button size="mini" @click="closes()">取消</el-button>
        </div>
        <div class="tableSearch tableSearchs">
          <!-- <i class="el-input__icon el-icon-search" @click="search()"></i> -->

          <el-form label-width="100px" class="demo-ruleForm">
            <el-form-item label="" label-width="15px">
              <el-input class="input" v-model="keyword" size="small" placeholder="输入商品名称或编号"></el-input>
            </el-form-item>
            <el-button style="margin-left:20px;margin-top:-20px;" @click="search()" size="small" type="primary">查询</el-button>
          </el-form>
        </div>
        <el-table :data="materielList" stripe border ref="multipleTable" tooltip-effect="dark" @selection-change="changeFun_good">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
          <el-table-column prop="name" label="商品" align="center"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
          <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
          <el-table-column prop="parameter" label="规格型号" align="center">
            <template slot-scope="scope">
              <div v-for="(item, index) in  scope.row.parameter" :key="index">
                <span v-if="item!=null">{{item.paramName}} :</span>
                <span v-if="item!=null">{{item.paramValue}} </span>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="purchasePrice" label="单价" align="center"></el-table-column> -->
          <!-- <el-table-column prop="goodsQuantity" label="库存数量" align="center"></el-table-column> -->
        </el-table>
        <div class="pageblock">
          <el-button size="mini" type="primary" class="Determine topage">确定</el-button>
          <el-pagination @size-change="handleSizeChange_good" @current-change="handleCurrentChange_good" :current-page="currentpage_good" :page-sizes="[20,40]" :page-size="pageSize_good" layout="total, sizes, prev, pager, next, jumper" :total="total_good">
          </el-pagination>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import addMaterial from "../../../components/AddMaterial";
import sdInput from "../../../components/SdInput";
import u from "@/util";
import {
  findGoodsListPage,
  getRepositoryListPage,
  addSupplies,
  leadRepertory
} from "@/api";

export default {
  data() {
    return {
      pickerOptions1: {
         disabledDate(time) {
            return time.getTime() > Date.now();
          },
        },//当前日期之后的不可选  
      entered: false,
      warehouseName: "",
      options: [],
      startCounting: true,
      dialogTableVisible_good: false,
      total_good: 0,
      pageSize_good: 20,
      currentpage_good: 1,
      keyword: "",
      materielList: [],
      tableData: [],
      formdata: {
        warehouse: "",
        creater: "",
        remark: ""
      },
      rules: {
        warehouse: [
          { required: true, message: "请选择录入仓库", trigger: "blur" }
        ]
      },
      userInfos: "",
      stagestocklist: []
    };
  },
  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      userInfo: state => state.userInfo,
      sub: state => state.sub,
      linkName: state => state.linkName,
      mobile: state => state.mobile,
      companyName: state => state.companyName,
      power: state => state.power,
      userId: state => state.userId,
    }),
    formdataTotal: function() {
      let totalPrice = 0;
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsAmount =
          this.tableData[i].purchasePrice * this.tableData[i].goodsNum;
        totalPrice +=
          this.tableData[i].purchasePrice * this.tableData[i].goodsNum;
      }
      this.formdata.purchaseAmount = totalPrice.toFixed(2);
      return isNaN(totalPrice) ? 0 : totalPrice.toFixed(2);
    }
  },
  components: { addMaterial, sdInput },
  created() {},
  methods: {
    // 分配权限
    setRole(key) {
      return u.selectTitle(this.power, key);
    },
    download() {
      window.open(
        "https://sd-picture-oss.oss-cn-beijing.aliyuncs.com/最新期初库存下载模板.xlsx"
      );
    },
    getwarehouseName(val) {
      this.stagestocklist.forEach(item => {
        if (item.openingInventoryState == "1" && item.id == val) {
          this.$message({
            type: "error",
            message: "该仓库已录入期初库存"
          });
          this.formdata.warehouse = "";
          this.$set(this, "entered", true);
        } else {
          this.entered = false;
        }
      });
      if (val) {
        this.tableData = [];
      }
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].id == val) {
          this.warehouseName = this.options[i].name;
          break;
        }
      }
    },
    addShop() {
      if (this.formdata.warehouse == "") {
        this.$message({
          type: "error",
          message: "请先选择录入仓库"
        });
      } else {
        this.dialogTableVisible_good = true;
        this.getGoods(this.pageSize_good, this.currentpage_good);
      }
    },
    // 上传文件
    uploading(event) {
      if (this.formdata.warehouse == "") {
        this.$message({
          type: "error",
          message: "请先选择录入仓库"
        });
        this.$refs.uploading.value = null;
      } else {
        this.file = event.target.files[0]; //获取文件
        var windowURL = window.URL || window.webkitURL;
        //创建图片文件的url
        this.src = windowURL.createObjectURL(event.target.files[0]);
        //取消默认行为
        // event.preventDefault();
        let warehouseName = "";
        for (let i = 0; i < this.options.length; i++) {
          if (this.options[i].id == this.formdata.warehouse) {
            warehouseName = this.options[i].name;
            break;
          }
        }
        let formdata = new FormData();
        formdata.append("file", this.file);
        formdata.append("orgId", this.merchantId);
        formdata.append("shopId", this.merchantId);
        formdata.append("shopName", this.companyName);
        formdata.append("repoId", this.formdata.warehouse);
        formdata.append("repoName", warehouseName);
        leadRepertory(formdata)
          .then(res => {
            if (res.code == "200") {
              this.$refs.uploading.value = null;
              this.loading = false;
              this.$message({
                showClose: true,
                message: res.msg,
                type: "success"
              });
            } else {
              this.$message({
                showClose: true,
                message: res.msg,
                type: "error"
              });
            }
          })
          .catch(error => {
            this.$refs.uploading.value = null;
          });
      }
    },
    save(val) {
      let goodsList = [];
      if (val == "none") {
        if (this.tableData.length > 0) {
          this.$message({
            type: "error",
            message: "已选择商品,需清空商品再上传零期初库存"
          });
          return false;
        } else {
          goodsList = [];
        }
      } else {
        if (this.tableData.length == 0) {
          this.$message({
            type: "error",
            message: "请选择商品"
          });
          return false;
        } else {
          let parameters = [];
          goodsList = this.tableData.map(function(item) {
            return {
              goodsId: item.id,
              goodsName: item.name,
              goodsUnit: item.goodsUnit,
              barCode: item.barCode,
              goodsQuantity: item.goodsNum,
              latestPrice: item.goodsPrice,
              goodsBatchNumber: item.goodsBatchNumber,
              goodsSpec: item.parameter,
              isBatch: item.isBatch,
              goodsCode:item.goodsCode,
              dateInProduced: item.dateInProduced
            };
          });
        }
      }
      let data = {
        creater: this.userId,
        shopId: this.merchantId,
        repoId: this.formdata.warehouse,
        repoName: this.warehouseName,
        shopName: this.companyName,
        goodsList: JSON.stringify(goodsList)
      };
      let a = true;
      goodsList.forEach((item) => {
        if (
          item.isBatch == "1" &&
          (item.goodsBatchNumber == "" || item.goodsBatchNumber == undefined)
        ) {
          a = false;
          return;
        }
      });
      let b = true;
      goodsList.forEach((item) => {
        if (
          item.isBatch == "1" &&
          (item.dateInProduced == "" || item.dateInProduced == undefined||item.dateInProduced == null)
        ) {
          b = false;
          return;
        }
      });
      if (a == false) {
        this.$message({
          type: "error",
          message: "请填写批次"
        });
      }else if(b == false){
         this.$message({
          type: "error",
          message: "选择生产日期"
        });
      } else {
        addSupplies(data).then(res => {
          if (res.code == "200") {
            this.$message({
              type: "success",
              message: res.msg
            });
            this.tableData = [];
            this.startCounting = false;
          }
        });
      }
    },
    //默认当前操作员
    init() {
      if (this.linkName != undefined&&this.linkName != "") {
        this.userInfos = this.linkName;
      } else {
        this.userInfos = this.mobile;
      }
      this.formdata.creater = this.userInfos;
    },
    repertory() {
      let data = {
        shopId: this.merchantId,
        status: "0"
      };
      getRepositoryListPage(data).then(res => {
        this.stagestocklist = res.data.list;
        for (let i = 0; i < res.data.list.length; i++) {
          //默认当前仓库
          let a = {
            id: res.data.list[i].id,
            name: res.data.list[i].repositoryName
          };
          this.options.push(a);
          // }
        }
      });
    },
    listenChooseDone(val) {
      this.tableData = val;
      for (let i = 0; i < this.tableData.length; i++) {
        this.tableData[i].goodsNum = 0;
        this.tableData[i].goodsPrice = 0;
      }
      this.dialogTableVisible_good = false;
      this.startCounting = true;
    },
    // listenKeyword(val) {
    //   this.materielKeyword = val;
    //   this.getGoods(this.pageSize_good, 1);
    // },
    // changeFun_good(val) {
    //   this.deleteList = val;
    // },
    getGoods(pageSize, pageNum) {
      let data = {
        name: this.keyword,
        pageSize: pageSize,
        pageNo: pageNum,
        shopId: this.merchantId,
        repositoryId: this.formdata.warehouse,
        status: "0"
      };
      findGoodsListPage(data).then(res => {
        this.materielList = res.data.list;
        this.total_good = res.data.total;
      });
    },
    handleSizeChange_good(val) {
      this.pageSize_good = val;
      this.currentpage_good=1
      this.getGoods(val, this.currentpage_good);
    },
    handleCurrentChange_good(val) {
      this.currentpage_good=val
      this.getGoods(this.pageSize_good, val);
    },
    handleDelete(val) {
      this.tableData.splice(val, 1);
    },
    search() {
      this.currentpage_good=1
      this.getGoods(this.pageSize_good, this.currentpage_good);
    },
    save_good() {
      // 点击选择完成 导出数据
      if (this.chooseData.length === 0) {
        this.$message({
          type: "error",
          message: "请先选择商品!"
        });
      } else {
        this.tableData = this.tableData.concat(this.chooseData);
        this.tableData = this.uniq(this.tableData);
        this.startCounting = true;
        this.closes();
      }
    },
    uniq(arr) {
      let newArr = [arr[0]];
      for (let i = 1; i < arr.length; i++) {
        let repeat = false;
        for (let j = 0; j < newArr.length; j++) {
          if (
            arr[i].id === newArr[j].id &&
            arr[i].isBatch == "0" &&
            newArr[j].isBatch == "0"
          ) {
            repeat = true;
            break;
          } else {
          }
        }
        if (!repeat) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },
    changeFun_good(val) {
      if (val) {
        this.chooseData = val;
      } else {
        this.chooseData = [];
      }
    },
    // toggleSelection (rows) {
    //   if (rows) {
    //     this.$refs.multipleTable.clearSelection();
    //     rows.forEach(row => {
    //       this.$refs.multipleTable.toggleRowSelection(row, true);
    //     });
    //   }
    // },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    closes() {
      this.dialogTableVisible_good = false;
      this.$refs.multipleTable.clearSelection();
      this.goodArray = [];
    }
  },
  mounted() {
    this.repertory();
    this.init();
    // this.getGoods(this.pageSize_good, 1);
  }
};
</script>
<style scoped>
.th-right {
  margin-top: 20px;
  width: 50%;
  min-width: 300px;
  float: right;
}
#app {
  text-align: left;
}
</style>
<style lang="less" scoped>
.stockstagestock {
  .file {
    position: relative;
    top: 10px;
    display: inline-block;
    background: #409eff;
    border: 1px solid #409eff;
    border-radius: 4px;
    padding: 7px 15px;
    margin: auto 10px;
    overflow: hidden;
    color: #fff;
    text-decoration: none;
    text-indent: 0;
    line-height: 12px;
    font-size: 12px;
    input {
      position: absolute;
      right: 0;
      top: 0;
      left: 0;
      bottom: 0;
      opacity: 0;
    }
  }
}
</style>
